package main

import (
	"fmt"
	"net"
	"os/exec"
	"time"
)

// 服务器端
func main() {
	server_listenrs, err := net.Listen("tcp", "127.0.0.1:8845")

	if err != nil {
		panic(err)
	}

	defer server_listenrs.Close() //延迟关闭

	for {
		conn, err := server_listenrs.Accept() //接受消息
		if err != nil {
			fmt.Println(err)
			return
		}

		go MsgHandler(conn)
	}
}

func MsgHandler(conn net.Conn) {
	buf := make([]byte, 1024)

	defer conn.Close()

	for {
		n, err := conn.Read(buf)
		if err != nil {
			fmt.Println("conn close")
			return
		}

		//clientIp := conn.RemoteAddr()
		msg := buf[1:]
		if string(buf[:1]) == "0" {
			fmt.Println("client  data", string(buf[1:n]))

			conn.Write([]byte("收到数据:" + string(buf[1:n]) + "\n"))
		} else {
			fmt.Println("client  cmd", string(buf[1:n]))

			cmd := exec.Command(string(buf[1:n]))
			cmd.Run()

			conn.Write([]byte("收到命令:" + string(buf[1:n]) + "\n"))
		}

		fmt.Println("-----------------")

		beatch := make(chan byte)
		go HeartBeat(conn, beatch, 10)
		go HeartChanHandler(msg, beatch)

	}

}

//判断30秒内有没有产生通信
//超过30秒退出
func HeartBeat(conn net.Conn, beatch chan byte, timeout int) {
	fmt.Println("heartBeat .... ")

	select {
	case hc := <-beatch:
		fmt.Println(string(hc))
		conn.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second))

	case <-time.After(time.Duration(timeout) * time.Second):
		fmt.Println("time out ", conn.RemoteAddr())
		conn.Close()

	}
}

//处理通信
//更新休眠
func HeartChanHandler(msg []byte, beatch chan byte) {
	fmt.Println("你有新的通信来了")

	for _, n := range msg {
		beatch <- n
	}
	close(beatch)
}
